<script setup lang='ts'>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { CircleCloseFilled, Plus } from '@element-plus/icons-vue'
import type { IUsersWrite } from '../../types/users'
import type { IRoles } from '../../types/roles'
import http from '../../api/http'
import { apiBaseURL, imgBaseURL } from '../../api/baseURL'

//props  读取父组件传递的 属性值 （只读）
// const props = defineProps(['dialogVisible'])
// const emit = defineEmits(['change'])

const dialogVisible = defineModel()
const emit = defineEmits<{ (e: 'refresh'): void }>()

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<IUsersWrite>({
    userId: 0,
    loginName: 'Test123',
    loginPwd: '123',
    userName: '测试用户',
    sex: '男',
    birthday: new Date(),
    phone: '18809898721',
    imgId: 0,
    roleId: 4,
    status: true,
    path: ''
})

//#region 头像上传
const handleAvatarSuccess = (res: any) => {
    ruleForm.imgId = res.data.imgId;
    ruleForm.path = res.data.path
    console.log(res.data.imgId)
}
//上传之前
const beforeAvatarUpload = (file: any) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'

    const isLtMB = file.size / 1024 / 1024 < 10

    if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 和 PNG 格式!')
    }
    if (!isLtMB) {
        ElMessage.error('上传头像图片大小不能超过 10MB!')
    }
    return (isJPG || isPNG) && isLtMB
}

//#endregion

//表单验证
const rules = reactive<FormRules<IUsersWrite>>({
    userName: [
        { required: true, message: '请输入姓名!', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在3-10个字符之间!', trigger: 'blur' },
    ],
    loginName: [
        { required: true, message: '请输入登录账户!', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3-20个字符之间!', trigger: 'blur' },
    ],
    loginPwd: [
        { required: true, message: '请输入登录密码!', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在3-20个字符之间!', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'change', }
    ],
    birthday: [
        { type: 'date', required: true, message: 'Please pick a date', trigger: 'change', }
    ],
    phone: [
        { required: true, message: '请输入手机号码!', trigger: 'blur' },
        { min: 11, max: 11, message: '长度为11的数字!', trigger: 'blur' },
    ],
    roleId: [
        { required: true, message: '请选择角色!', trigger: 'change', }
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {

        if (valid) {
            //axios 提交后台

            http.post('Users', ruleForm).then(res => {
                if (res.code == '1') {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    dialogVisible.value = false
                    emit('refresh')
                }
                else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }

            }).catch(err => {
                console.log('err: ', err);
            })


            //关闭弹窗 并刷新列表页面数据
            dialogVisible.value = false
            emit('refresh')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const roles: IRoles[] = reactive([])

onMounted(() => {
    //获取用户角色下拉列表
    http.get<IRoles[]>('Roles')
        .then(res => {
            roles.push(...res.data)
        })
        .catch(err => {
            console.log('err: ', err);
        })

})

</script>

<template>

    <el-dialog v-model="dialogVisible" :show-close="false" width="500" center>
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass"></h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left">
                        <CircleCloseFilled />
                    </el-icon>
                    关闭
                </el-button>
            </div>
        </template>

        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="角色" prop="roleId">
                <el-select v-model="ruleForm.roleId" placeholder="请选择角色">
                    <el-option v-for="(item, index) in roles" :key="index" :label="item.roleName" :value="item.roleId">
                        {{ item.roleName }}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio value="男">男</el-radio>
                    <el-radio value="女">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="头像" prop="imgId">
                <el-upload class="avatar-uploader" :action="apiBaseURL + 'Upload'" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="ruleForm.path" :src="imgBaseURL + ruleForm.path" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon el-upload">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="账户" prop="loginName">
                <el-input v-model="ruleForm.loginName" />
            </el-form-item>
            <el-form-item label="密码" prop="loginPwd">
                <el-input v-model="ruleForm.loginPwd" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="ruleForm.phone" />
            </el-form-item>


            <el-form-item label="出生日期" required>
                <el-col :span="11">
                    <el-form-item prop="birthday">
                        <el-date-picker v-model="ruleForm.birthday" type="date" aria-label="Pick a date"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD" placeholder="Pick a date"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="ruleForm.status" />
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>


<style scoped>
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
}

.avatar {
    width: 128px;
    height: 128px;
    display: block;
}
</style>